import {
    userLoginPassword,
    userLoginBind,
    getCode
} from '../../api/login'

import {
    passwordJsencrypt
} from '../../utils/util'
// pages/login/login.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // ABCD-98W-89565-KJ9
        // 555666
        TYPE: 0, //0 验证码 1密码
        account: "",
        password: "",
        code: "",
        cjh: "",
        mobile: "",
        nums: 60,
        btntxt: '发送验证码',
        disabled: false,
        agree: [],
        isRember: false,
        wxVsersion:''
    },
    checkboxChange(e) {
        this.setData({
            agree: e.detail.value
        })
    },
    checkboxChangePWD(e) {
        this.setData({
            isRember: e.detail.value
        })
    },
    handleOPEN() {
        console.log(111111)
        wx.openPrivacyContract()
    },
    onShow() {
        wx.hideLoading()
        if (wx.getStorageSync('account')) {
            this.setData({
                account: wx.getStorageSync('account'),
                password: wx.getStorageSync('password')
            })
        }
        this.setData({
            wxVsersion:wx.getAccountInfoSync().miniProgram.version
        })
    },
    handleGetCODE() {
        getCode({
            mobile: this.data.mobile
        }).then(res => {
            console.log(res)
            if (!res) {
                const timer = setInterval(() => {
                    if (this.data.nums <= 0) {
                        this.setData({
                            nums: 60,
                            btntxt: '发送验证码',
                            disabled: false
                        })
                        clearInterval(timer)
                    } else {
                        this.setData({
                            nums: this.data.nums - 1,
                            btntxt: `等${this.data.nums}s后发送`,
                            disabled: true
                        })
                    }
                }, 1000);
            }
        })
    },
    handleChangeType(e) {
        console.log(e)
        this.setData({
            TYPE: e.currentTarget.dataset.type
        })
    },
    handleChangeCjh(e) {
        this.setData({
            cjh: e.detail.value
        })
    },
    handleChangeMobile(e) {
        this.setData({
            mobile: e.detail.value
        })
    },
    handleChangeCode(e) {
        this.setData({
            code: e.detail.value
        })
    },
    handleChangeAccount(e) {
        this.setData({
            account: e.detail.value
        })
    },
    handleChangePwd(e) {
        this.setData({
            password: e.detail.value
        })
    },
    // 行数
    hexArrayToNumber(hexArray) {
        const hexString = hexArray.map(hex => hex.toString(16).padStart(2, '0')).join('');
        const number = parseInt(hexString, 16);
        return number;
    },
    // 时间
    bluetoothDataToNumber(data) {
        const reversedData = data.reverse();
        const hexString = reversedData.map(byte => byte.toString(16).padStart(2, '0')).join('');
        const number = parseInt(hexString, 16);
        return number;
    },
    // id
    bluetoothDataToID(arr) {
        let str = ''
        let finalstr = ''
        if (arr[3] == 0) {
            finalstr = ''
        } else {
            finalstr = 'x'
        }
        console.log(arr[3].toString(16), arr[2].toString(16), arr[1].toString(16), arr[0].toString(16), 'id')
        console.log((arr[3] & 0x1f).toString(16), 'id')
        // return '0x'+ (arr[3] & 0x1f).toString(16) + arr[2].toString(16) + arr[1].toString(16) + arr[0].toString(16) + finalstr
        return '0x'+ (arr[3] & 0x1f).toString(16) + arr[2].toString(16) + arr[1].toString(16) + arr[0].toString(16) + finalstr
       
    },
    handleTest() {
        // const arr = [0x2E, 0x60, 0x11, 0x02, 0x00, 0x00, 0x00, 0x02, 0x83, 0x1F, 0x00, 0x00, 0x23, 0x56, 0xF4, 0x26, 0x98, 0x01, 0x01, 0x00, 0xBB,]
        const arr = [0x2E ,0x60 ,0x16,0x02,0x00, 0x00,0x00, 0xBA, 0x2E ,0x79 ,0x00 ,0x00 ,0x28 ,0x56 ,0xF4 ,0x08 ,0x98 ,0xA6 ,0x1D ,0xD0 ,0x07 ,0xE8 ,0x03 ,0x64, 0x0F ,0x1C]
        console.log(this.hexArrayToNumber([arr[4], arr[5], arr[6], arr[7]]))
        console.log(this.bluetoothDataToNumber([arr[8], arr[9], arr[10], arr[11]]))
        console.log((arr[12] >> 5) & 0x03, 'CAN通道')
        console.log(arr[12] & 0x10, '1TX ,0RX')
        console.log(arr[12] & 0x0f, 'DLC')
        console.log(this.bluetoothDataToID([arr[13], arr[14], arr[15], arr[16]]))
        const slicedArray = arr.slice(17,arr.length-1);
        const  time = this.bluetoothDataToNumber([arr[8], arr[9], arr[10], arr[11]])
        const  Chl =  (arr[12] >> 5) & 0x03
        const  ID = this.bluetoothDataToID([arr[13], arr[14], arr[15], arr[16]])
        let  txrx = ''
        arr[12] & 0x10 == 0 ?txrx='RX':txrx='TX'
        const  DLC = arr[12] & 0x0f
       
        let row = []
        row.push(time)
        row.push('CAN' + Chl)
        row.push(ID)
        row.push(txrx)
        row.push(DLC)
        slicedArray.forEach(el=>{
            row.push(el.toString(16))
        })
        console.log(JSON.stringify(row)+'\n\r')
        const fs = wx.getFileSystemManager();
        console.log( wx.env.USER_DATA_PATH + '/example.txt')
        fs.writeFile({
            filePath: wx.env.USER_DATA_PATH + '/example.txt',
            data:  JSON.stringify(row)+'\n\r',
            encoding: 'utf8',
            success: function (res) {
                console.log(res)
              console.log('ArrayBuffer已成功转换为文件');
            
            },
            fail: function (err) {
              console.error('转换失败：', err);
            }
        })
    },
    handleLogin() {


        if (this.data.TYPE == 0) {
            if (!this.data.cjh) {
                wx.showToast({
                    title: '输入车架号',
                    icon: 'none'
                })
                return
            }
            if (!this.data.code) {
                wx.showToast({
                    title: '输入验证码',
                    icon: 'none'
                })
                return
            }
            if (!this.data.mobile) {
                wx.showToast({
                    title: '输入手机号',
                    icon: 'none'
                })
                return
            }
            if (!this.data.agree[0]) {
                wx.showToast({
                    title: '请同意用户手册和隐私政策',
                    icon: 'none'
                })
                return
            }
            userLoginBind({
                mobile: this.data.mobile,
                cjh: this.data.cjh,
                checkCode: this.data.code
            }).then(res => {
                if (res.token) {
                    wx.setStorageSync('userId', res.userId)
                    wx.setStorageSync('token', res.token)
                    wx.setStorageSync('cjh', res.cjh)
                    wx.setStorageSync('lastLogin', res.lastLogin)
                    wx.setStorageSync('canAddCjh', res.canAddCjh)
                    wx.setStorageSync('isAdmin', res.isAdmin ? res.isAdmin : 0)
                    wx.switchTab({
                        url: '/pages/params/params',
                    })
                }
            })
        } else {
            if (!this.data.account) {
                wx.showToast({
                    title: '输入车架号或手机号',
                    icon: 'none'
                })
                return
            }
            if (!this.data.password) {
                wx.showToast({
                    title: '输入密码',
                    icon: 'none'
                })
                return
            }
            if (!this.data.agree[0]) {
                wx.showToast({
                    title: '请同意用户手册和隐私政策',
                    icon: 'none'
                })
                return
            }
            if (this.data.isRember) {
                wx.setStorageSync('password', this.data.password)
            }
            userLoginPassword({
                account: this.data.account,
                password: passwordJsencrypt(this.data.password)
            }).then(res => {
                console.log(res)
                if (res.token) {
                    wx.setStorageSync('userId', res.userId)
                    wx.setStorageSync('token', res.token)
                    wx.setStorageSync('cjh', res.cjh)
                    wx.setStorageSync('lastLogin', res.lastLogin)
                    wx.setStorageSync('canAddCjh', res.canAddCjh)
                    wx.setStorageSync('isAdmin', res.isAdmin ? res.isAdmin : 0)
                    wx.setStorageSync('account', this.data.account)
                    // wx.setStorageSync('password',this.data.password)

                    wx.switchTab({
                        url: '/pages/params/params',
                    })
                }

            })
        }

    }
})